package cn.lx.es.query.listener;

import cn.lx.es.query.annotation.ESMetaData;
import cn.lx.es.query.index.EsIndexMangerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import java.util.Map;

/**
 * @author wcy
 * @version 1.0
 * @description: 监听应用启动事件，自动创建ES索引
 * @date 2025-07-02 上午11:50
 */
public class CreateIndexListener implements ApplicationListener, ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(CreateIndexListener.class);

    private EsIndexMangerService esIndexMangerService;

    private ApplicationContext applicationContext;

    public CreateIndexListener() {
    }

    public CreateIndexListener(EsIndexMangerService esIndexMangerService) {
        this.esIndexMangerService = esIndexMangerService;
    }

    /**
     * 扫描ESMetaData注解的类，并自动创建索引mapping
     *
     * @param event
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        Map<String, Object> beansWithAnnotationMap = this.applicationContext.getBeansWithAnnotation(ESMetaData.class);
        beansWithAnnotationMap.forEach((beanName, bean) -> {
                    try {
                        if (!esIndexMangerService.exists(bean.getClass())) {
                            esIndexMangerService.createIndex(bean.getClass());
                            logger.info("启动创建索引成功");
                        }
                    } catch (Exception e) {
                        logger.error("创建索引不成功", e);
                    }
                }
        );
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
